package com.ndphu.comic.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.ndphu.comic.io.Utils;

public class DatabaseHelper extends SQLiteOpenHelper {
	// All Static variables
	// Database Version
	private static final int DATABASE_VERSION = 1;

	// Database Name
	private static final String DATABASE_NAME = "contactsManager";

	// Contacts table name
	private static final String TABLE_PAGE_CACHE = "page_cache";

	// Contacts Table Columns names
	private static final String KEY_ID = "id";
	private static final String KEY_URL = "url";
	private static final String KEY_URL_HASH = "url_hash";
	private static final String KEY_DATA = "data";

	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_PAGE_CACHE + "("
                + KEY_ID + " INTEGER PRIMARY KEY," 
				+ KEY_URL + " TEXT,"
                + KEY_URL_HASH + " TEXT," 
                + KEY_DATA + " BLOB" 
				+ ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_PAGE_CACHE);
        // Create tables again
        onCreate(db);
	}
	
	public void addPageCache(String url, byte[] data) {
		String hashUrl = Utils.md5(url);
		SQLiteDatabase db = this.getWritableDatabase();
		ContentValues values = new ContentValues();
	    values.put(KEY_URL, url); // Contact Name
		values.put(KEY_URL_HASH, hashUrl);
	    values.put(KEY_DATA, data);
		// Inserting Row
		db.insert(TABLE_PAGE_CACHE, null, values);
	    db.close(); // Closing database connection
	}
	
	public byte[] getCachedPage(String url) {
		String hashUrl = Utils.md5(url);
		SQLiteDatabase db = this.getReadableDatabase();
		 
	    Cursor cursor = db.query(TABLE_PAGE_CACHE, new String[] { KEY_DATA }, KEY_URL_HASH + "=?",
	            new String[] { hashUrl }, null, null, null, null);
	    if (cursor != null && cursor.moveToFirst()) {
	        byte[] data = cursor.getBlob(0);
		    return data;
	    } else {
	    	return null;
	    }
	}

}
